﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

namespace Common.Tools
{
    /// <summary>
    /// 解析JSON，仿Javascript风格
    /// </summary>
    public static class JSON
    {
        //不能使用Linq
        public static T Parse<T>(string jsonString)
        {
            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
            {
                return (T)new DataContractJsonSerializer(typeof(T)).ReadObject(ms);
            }
        }

        public static string Stringify(object jsonObject)
        {
            using (var ms = new MemoryStream())
            {
                new DataContractJsonSerializer(jsonObject.GetType()).WriteObject(ms, jsonObject);
                return Encoding.UTF8.GetString(ms.ToArray());
            }
        }


        public static Dictionary<string, object> Parse(string jsonString)
        {
            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
            {
                return (Dictionary<string, object>)new DataContractJsonSerializer(typeof(Dictionary<string, object>)).ReadObject(ms);
            }
        }

        public static Dictionary<string, object> Parse(byte[] jsonBytes)
        {
            using (var ms = new MemoryStream(jsonBytes))
            {
                return (Dictionary<string, object>)new DataContractJsonSerializer(typeof(Dictionary<string, object>)).ReadObject(ms);
            }
        }
    }
}
